<template>
   <el-dialog title="编辑用户角色" :visible.sync="formVisible" width="500px">
    <el-form :rules="formRules" ref="formEl" :model="editForm" size="small">
      <el-form-item prop="username" label="用户名" label-width="80px">
        <el-input disabled v-model="editForm.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item prop="email" label="角色" label-width="80px">
        <!--
          el-select 会自动让 el-options 的 value 与 editForm.rid 相等的被选中
         -->
        <el-select v-model="editForm.rid" placeholder="请选择">
          <el-option :value="-1" label="请选择"></el-option>
          <el-option
            v-for="item in roles"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="formVisible = false">取 消</el-button>
      <el-button type="primary" @click.prevent="handleEditRole">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getById as getUserById, updateUserRoleByUserId } from '@/api/user'
import { getRoleList } from '@/api/role'
export default {
  name: 'UserEditRole',
  data () {
    return {
      formVisible: false,
      editForm: {
        username: '',
        email: '',
        mobile: ''
      },
      roles: [],
      formRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async handleEditRole () {
      const { id: userId, rid: roleId } = this.editForm
      const { meta } = await updateUserRoleByUserId(userId, roleId)
      if (meta.status === 200) {
        // 关闭对话框
        this.formVisible = false
        this.$message({
          type: 'success',
          message: '分配用户角色成功'
        })
      }
    },
    async showEditRoleDialog (item) {
      const { data, meta } = await getUserById(item.id)
      if (meta.status === 200) {
        this.editForm = data
        this.formVisible = true // 显示弹框
      }
      const { data: roleData, meta: roleMeta } = await getRoleList()
      if (roleMeta.status === 200) {
        this.roles = roleData
      }
    }
  }
}
</script>
<style scoped>
</style>
